package com.juyu.miliao.api.dao.elasticsearch;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.FindDynamicCommentInfo;
import com.juyu.miliao.api.domain.vo.FindDynamicCommentVO;
import com.juyu.miliao.api.domain.vo.FindDynamicVO;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.util.DateUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 */
@Repository
public class FindDynamicCommentElasticsearch {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserInfoCache userInfoCache;



    public void addFindDynamicCommentInfo(FindDynamicCommentInfo findDynamicCommentInfo) throws IOException {
        IndexRequest request = new IndexRequest("find_dynamic_comment_info","findDynamicCommentInfo",
                findDynamicCommentInfo.getId()+"");

        request.source(objectMapper.writeValueAsString(findDynamicCommentInfo), XContentType.JSON);

        restHighLevelClient.index(request,RequestOptions.DEFAULT);
    }

    public long getCount(int findId) throws IOException {
        SearchRequest searchRequest = new SearchRequest("find_dynamic_comment_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("findId",findId);

        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.size(0);
        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        return res.getHits().getTotalHits();
    }

    public List<FindDynamicCommentVO> selectPage(int findId, Integer page, Integer pageSize) throws IOException {
        int startNum = PageUtil.getOffset(page, pageSize);
        SearchRequest searchRequest = new SearchRequest("find_dynamic_comment_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("findId",findId));
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.from(startNum);
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));

        FieldSortBuilder fieldSortBuilder = new FieldSortBuilder("commentTime").order(SortOrder.DESC);
        searchSourceBuilder.sort(fieldSortBuilder);

        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

        SearchHit[] hits = res.getHits().getHits();
        List<FindDynamicCommentVO> list = new ArrayList<>();
        for(SearchHit hit : hits){
            FindDynamicCommentVO findDynamicCommentVO =objectMapper.readValue(hit.getSourceAsString(),
                    FindDynamicCommentVO.class);
            setFindDynamicCommentUserInfo(findDynamicCommentVO);

            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String showTime = DateUtil.getShowTime(LocalDateTime.parse(findDynamicCommentVO.getCommentTime(), df));
            findDynamicCommentVO.setShowTime(showTime);
            list.add(findDynamicCommentVO);
        }
        return list;
    }

    private void setFindDynamicCommentUserInfo(FindDynamicCommentVO findDynamicCommentVO) {
        UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(findDynamicCommentVO.getFromUserId());
        findDynamicCommentVO.setNickName(userCacheVo.getNickName());
        findDynamicCommentVO.setVGrade(userCacheVo.getVGrade());
        findDynamicCommentVO.setAge(userCacheVo.getAge());
        findDynamicCommentVO.setSex(userCacheVo.getSex());
        findDynamicCommentVO.setIsHost(userCacheVo.getIsHost());
        findDynamicCommentVO.setVipLevel(userCacheVo.getVipLevel());
        findDynamicCommentVO.setIcon(userCacheVo.getIcon());
        findDynamicCommentVO.setStar(userCacheVo.getStar());
        findDynamicCommentVO.setIsVip(userCacheVo.getIsVip());
        findDynamicCommentVO.setMGrade(userCacheVo.getMGrade());
        findDynamicCommentVO.setEnergyGrade(userCacheVo.getUserLevel()
                .getEnergyGrade());

        String levelPic = userCacheVo.getUserLevel().getLevelPic();
        findDynamicCommentVO.setLevelPic(levelPic==null ? "":levelPic);

        Integer hostLevel = userCacheVo.getHostUserLevel().getHostUserGrade();
        findDynamicCommentVO.setHostUserGrade(hostLevel==null ? 0: hostLevel);
        String hostUserGradePic = userCacheVo.getHostUserLevel().getHostUserGradePic();
        findDynamicCommentVO.setHostUserGradePic(hostUserGradePic==null ? "":hostUserGradePic);


    }

    public FindDynamicCommentInfo getFindDynamicCommentInfoByCommentId(long commentId) throws IOException {
        SearchRequest searchRequest = new SearchRequest("find_dynamic_comment_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("id",commentId));
        searchSourceBuilder.query(boolQueryBuilder);


        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

        SearchHit[] hits = res.getHits().getHits();
        List<FindDynamicCommentInfo> list = new ArrayList<>();
        for(SearchHit hit : hits){
            FindDynamicCommentInfo findDynamicComment =objectMapper.readValue(hit.getSourceAsString(),
                    FindDynamicCommentInfo.class);
            list.add(findDynamicComment);
        }

        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }
}
